const cheerio = require('cheerio');
const fs = require('fs');
const readline = require('readline');
// 获取命令行参数 移除前两个元素，只保留实际参数
const args = process.argv.slice(2);
const BOOT_CDN = "https://www.bootcdn.cn/"
// 当前工具包的版本
const VERSION = '1.0.0'
const AUTHOR = '饶奇奇'
// 下载指定包 jquery@版本
const installCommand = 'i'
// 查看有哪些版本的包
const listCommand = 'list'
// 查看帮助文档
const helpCommand = '--help'
// 查看当前版本
const versionCommand = "-v"
// 搜索包
const searchCommand = 'search'
// 查看有哪些版本的
const getDownloadPackeUrl = (html) => {
    return new Promise((resovle, reject) => {
        const $ = cheerio.load(html);
        console.log("当前版本下存在这些文件")
        url_link = $('.library-url').each((index, element) => {
            const text = $(element).text();
            console.log(text.split('/')[text.split('/').length - 1])
        });
    })
}
const indexPackage = (packageName) => fetch(BOOT_CDN + packageName).then(response => response.text())
/**
 * 
 * @param {*} packageName 
 * @param {*} type 是否显示历史版本 display显示
 * @returns 
 */
const searchPackage = async (packageName, type="display") => {
    const html = await indexPackage(packageName)
    const $ = cheerio.load(html);
    //console.log("$", $('.dropdown-menu.dmenuver>li'))
    if (type === 'display') {
        $('.dropdown-menu.dmenuver>li').each((index, element)=> {
            const text = $(element).text();
            console.log(text)
        })
    }
    return $('.dropdown-menu.dmenuver>li').last().text()
}
// 下载函数
const install = async (packageName) => {
    // 检查是否指定版本,没有版本直接指定最新版
    if (packageName) {
        // 拆分版本,拼接版本
        let [name, version] = packageName.split('@')
        // 不存在版本
        if (!version) {
            //下载最新版本
            version = await searchPackage(packageName, 'no')
        }
        const html = await fetch(BOOT_CDN + name + "/" + version)
        .then(response => response.text())
        // 让用户选择该版本下对应的文件
        const $ = cheerio.load(html);
        console.log(`当前版本${name}@${version}下存在这些文件`)
        url_link = $('.library-url').each((index, element) => {
            const text = $(element).text();
            console.log(`${index + 1}:` + text.split('/')[text.split('/').length - 1])
        });
        // 让用户选择要下载的包
        let downloadLink = ""
        let filename = ""
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
        });
        await new Promise((resovle, reject) => {
            rl.question('请输入下载序号：', (name) => {
                downloadLink = $('.library-url').eq(Number(name) - 1).text()
                filename = downloadLink.split("/")[downloadLink.split("/").length - 1]
                rl.close();
                resovle()
            });
        })
        console.log(downloadLink)
        // 下载依赖
        const js_conent = await fetch(downloadLink).then(response => response.text())
        if (js_conent !== 'File Not Found') {
            // 检查文件夹是否存在
            if (!fs.existsSync("./node_modules")) {
                // 创建文件夹
                fs.mkdirSync("./node_modules");
            } 
            // 写入文件
            fs.writeFileSync(`./node_modules/${filename}`, js_conent);
            console.log("下载完毕")
        } else {
            console.log("文件不存在请选择其他文件或者其他版本")
        }
        
    } else {
        console.log("没有指定参数,请重试")
    }
}



function main() {
    const args = process.argv.slice(2);
    if (installCommand === args[0]) {
        console.log("执行下载命令")
        install(args[1])
    } else if (helpCommand === args[0]) {
        console.log("查看文档")
    } else if (listCommand === args[0]) {
        console.log("查看有哪些版本的包")
    } else if (versionCommand === args[0]) {
        console.log('fast-chrome-plugin 版本1.0.0 作者:饶奇奇')
    } else if (searchCommand === args[0]) {
        searchPackage(args[1])
    }
}
main()